<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '分类任务',
  },
}
</route>
<template>
  <view class="category-tasks-page">
    <!-- 自定义导航栏 -->
    <view
      class="custom-nav-bar bg-white p-4 border-b border-gray-200 flex justify-between items-center"
      :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
    >
      <view class="flex items-center">
        <text class="i-fa-solid:chevron-left text-lg mr-2" @click="goBack"></text>
        <text class="text-xl font-semibold">{{ categoryName }}</text>
      </view>
      <view class="text-blue-500" @click="createTask">
        <text class="i-fa-solid:plus"></text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 任务列表 -->
    <view v-else class="task-list-container">
      <!-- 如果没有任务 -->
      <view v-if="tasks.length === 0" class="empty-state">
        <image class="empty-image" src="/static/images/empty-task.png" mode="aspectFit"></image>
        <text class="empty-text">该分类暂无任务</text>
        <text class="empty-subtext">点击右上角按钮添加新任务</text>
      </view>

      <!-- 有任务时显示任务列表 -->
      <view v-else class="task-list">
        <view
          v-for="task in tasks"
          :key="task.id"
          class="task-item"
          @click="goToTaskDetail(task.id)"
        >
          <view class="task-checkbox" :class="{ checked: task.completed }" @click.stop="toggleTaskComplete(task)">
            <view v-if="task.completed" class="i-fa-solid:check text-white"></view>
          </view>
          <view class="task-content">
            <view class="task-header">
              <text class="task-title" :class="{ 'line-through': task.completed }">{{ task.title }}</text>
              <view
                v-if="task.priority && !task.completed"
                :class="[
                  'priority-tag',
                  {
                    'priority-high': task.priority === 'high',
                    'priority-medium': task.priority === 'medium',
                    'priority-low': task.priority === 'low',
                  },
                ]"
              ></view>
            </view>
            <view v-if="(task.date || task.timeRange) && !task.completed" class="task-meta">
              <view v-if="task.date" class="meta-item">
                <text class="i-fa-solid:calendar-alt meta-icon"></text>
                <text class="meta-text">{{ task.date }}</text>
              </view>
              <view v-if="task.timeRange" class="meta-item">
                <text class="i-fa-solid:clock meta-icon"></text>
                <text class="meta-text">{{ task.timeRange }}</text>
              </view>
            </view>
            <view v-if="task.completed" class="task-meta">
              <view class="meta-item">
                <text class="i-fa-solid:check-circle meta-icon"></text>
                <text class="meta-text">{{ formatCompletedDate(task.updatedAt) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'CategoryTasksPage',
})

import { ref, onLoad } from 'vue'
import { taskService } from '@/services/task-service'
import type { Task } from '@/services/task-service'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 数据状态
const loading = ref(true)
const tasks = ref<Task[]>([])
const categoryId = ref('')
const categoryName = ref('分类任务')

/**
 * 加载任务列表
 */
const loadTasks = async () => {
  if (!categoryId.value) return
  
  loading.value = true
  try {
    // 获取分类下的所有任务
    tasks.value = await taskService.getTasksByCategoryId(categoryId.value)
    
    // 根据是否完成和优先级进行排序
    tasks.value.sort((a, b) => {
      // 首先按照是否完成排序
      if (a.completed !== b.completed) {
        return a.completed ? 1 : -1
      }
      
      // 未完成的任务按优先级排序
      if (!a.completed) {
        const priorityOrder = { high: 1, medium: 2, low: 3 }
        return priorityOrder[a.priority] - priorityOrder[b.priority]
      }
      
      // 已完成的任务按更新时间倒序排列（最近完成的在前面）
      return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
    })
  } catch (error) {
    console.error('加载分类任务失败:', error)
    uni.showToast({
      title: '加载任务失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 切换任务完成状态
 */
const toggleTaskComplete = async (task: Task) => {
  try {
    const newStatus = !task.completed
    const success = await taskService.completeTask(task.id, newStatus)
    
    if (success) {
      // 更新本地数据
      task.completed = newStatus
      if (newStatus) {
        task.updatedAt = new Date().toISOString()
      }
      
      // 重新排序列表
      loadTasks()
      
      // 显示操作结果提示
      uni.showToast({
        title: newStatus ? '已完成任务' : '已恢复任务',
        icon: 'success',
        duration: 1500
      })
    } else {
      throw new Error('操作失败')
    }
  } catch (error) {
    console.error('更新任务状态失败:', error)
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none',
      duration: 1500
    })
    
    // 失败时重新加载
    loadTasks()
  }
}

/**
 * 跳转到任务详情页
 */
const goToTaskDetail = (id: string) => {
  uni.navigateTo({
    url: `/pages/task/detail?id=${id}`,
  })
}

/**
 * 创建新任务
 */
const createTask = () => {
  uni.navigateTo({
    url: `/pages/task/edit?categoryId=${categoryId.value}`,
  })
}

/**
 * 格式化完成日期
 */
const formatCompletedDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天完成'
  } else if (diffDays === 1) {
    return '昨天完成'
  } else {
    return `${date.getMonth() + 1}月${date.getDate()}日完成`
  }
}

/**
 * 返回上一页
 */
const goBack = () => {
  uni.navigateBack()
}

// 页面加载时获取参数并加载任务
onLoad((options) => {
  if (options && options.categoryId) {
    categoryId.value = options.categoryId
    
    if (options.categoryName) {
      categoryName.value = decodeURIComponent(options.categoryName)
    }
    
    loadTasks()
  } else {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    })
    setTimeout(() => {
      goBack()
    }, 1500)
  }
})
</script>

<style lang="scss">
.category-tasks-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f2f2f7;
}

.loading-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid rgba(0, 122, 255, 0.1);
  border-top-color: #007aff;
  border-radius: 50%;
  animation: spin 1s infinite linear;
}

.loading-text {
  margin-top: 12px;
  font-size: 14px;
  color: #8e8e93;
}

.task-list-container {
  flex: 1;
  width: 100%;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 0 20px;
}

.empty-image {
  width: 150px;
  height: 150px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  font-weight: 500;
  color: #8e8e93;
  margin-bottom: 8px;
}

.empty-subtext {
  font-size: 14px;
  color: #8e8e93;
  text-align: center;
}

.task-list {
  background-color: white;
}

.task-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e5e5e5;
}

.task-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  margin-right: 16px;
  border: 2px solid #007aff;
  border-radius: 50%;
}

.task-checkbox.checked {
  background-color: #007aff;
}

.task-content {
  flex: 1;
}

.task-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.task-title {
  font-size: 16px;
  color: #000;
}

.line-through {
  text-decoration: line-through;
  color: #8e8e93;
}

.priority-tag {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.priority-high {
  background-color: #ff3b30;
}

.priority-medium {
  background-color: #ff9500;
}

.priority-low {
  background-color: #34c759;
}

.task-meta {
  display: flex;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-right: 12px;
}

.meta-icon {
  font-size: 12px;
  color: #8e8e93;
  margin-right: 4px;
}

.meta-text {
  font-size: 12px;
  color: #8e8e93;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style> 